import React from "react";

import BaseComponent from "../../../../redare/components/BaseComponent";
import PlatformPresenter from "../../.gen/presenter/component/core/PlatformPresenter";
import {Row} from "antd";
import Grid from "../../../../redare/components/grid/Grid";
import Window from "../../../../redare/components/modal/Window";
import RoleForm from "./RoleForm";
import Button from "../../../../redare/components/common/Button";
import FunPermission from "../permission/FunPermission";
import {isLoginUserInRootPlatform} from "../../utils/WorkbenchUtil";
import {getAbsolutePosition} from "../../../../redare/utils/DocumentUtils";

export default class RoleManage extends BaseComponent {

    static defaultProps = {
        platform: undefined,
        onRoleSelected: undefined
    };

    constructor(props) {
        super(props);
        this.presenter = new PlatformPresenter(this);
        this._isRootPlatform = isLoginUserInRootPlatform();
        this._domId = `${this.props.platform}-role-grid`;
    }

    componentDidMount() {
        this._findRoleList();
        let grid = document.getElementById(this._domId);
        let {top} = getAbsolutePosition(grid);
        if (top) {
            this.setState({offsetTop: top + 70});
        } else {
            this.setState({offsetTop: 200});
        }
    }

    _findRoleList() {
        let {platform} = this.props;
        this._onRoleChange(null, false);
        if (this._isRootPlatform) {
            this.presenter.findRoleList({platform, type: 1}, {returnAll: true}, (result) => {
                this.grid.setData(result.data);
            });
        } else {
            this.presenter.findRoleList({platform, platformUnionUserPlatform: true}, {returnAll: true}, (result) => {
                this.grid.setData(result.data);
            });
        }
    }

    _onRoleChange(record, selected) {
        let role = null;
        if (selected) {
            role = record;
            this.setState({roleId: [record.id]});
        } else {
            this.setState({roleId: []});
        }
        if (this.props.onRoleSelected) {
            this.props.onRoleSelected(role);
        }
    }

    _onAddClick() {
        this._win = Window.show(
            <RoleForm onCancel={() => {
                this._win.close();
            }}
                      platform={this.props.platform}
                      onAddSuccess={() => {
                          this._win.close();
                          this._findRoleList();
                      }}
            />,
            {title: '添加角色'});
    }

    _onEditClick({record, index}) {
        this._win = Window.show(
            <RoleForm onCancel={() => {
                this._win.close();
            }}
                      id={record.id}
                      onEditSuccess={() => {
                          this._win.close();
                          this._findRoleList();
                      }}
            />,
            {title: '编辑角色'});
    }

    _onDelClick({record, index}) {
        this.confirm('确定要删除该角色吗？', () => {
            this.presenter.delRole({id: record.id}, {}, () => {
                this._findRoleList({curPage: this.grid.getCurPage()});
            });
        });
    }

    render() {
        return (
            <>
                <Row style={({paddingBottom: 10})}>
                    <FunPermission funId="WebPlatformRoleAdd">
                        <Button size="middle"
                                type="primary"
                                onClick={this._onAddClick.bind(this)}>添加</Button>
                    </FunPermission>
                </Row>
                <Grid
                    ref={(o) => {
                        this.grid = o
                    }}
                    id={this._domId}
                    scroll={{y: window.document.body.clientHeight - this.state.offsetTop || 0}}
                    _showPage={false}
                    rowKey={(r) => r.id}
                    size="small"
                    rowSelection={({
                        selectedRowKeys: this.state.roleId,
                        hideDefaultSelections: true,
                        columnTitle: '选择',
                        onSelect: this._onRoleChange.bind(this)
                    })}
                    _onRowClick={({record}) => {
                        let selected = true;
                        let curRoleId = (this.state.roleId || [])[0];
                        if (curRoleId && curRoleId === record.id) {
                            selected = false;
                        }
                        this._onRoleChange(record, selected);
                    }}
                    columns={[
                        {
                            title: '角色名称',
                            dataIndex: 'name',
                            render: (value, record) => {
                                let {admin, defaults, des, name} = record;
                                if (admin || defaults) {
                                    return (
                                        <div>
                                            <b>{name}</b>（<i>{admin ? '管理员' : '默认'}</i>）
                                            <div style={({color: '#bbb'})}>{des}</div>
                                        </div>
                                    )
                                }
                                return (
                                    <div>
                                        <b>{name}</b>
                                        <div style={({color: '#bbb'})}>{des}</div>
                                    </div>
                                )
                            }
                        },
                        {
                            title: '角色类型',
                            dataIndex: 'type',
                            align: 'center',
                            render: (value, record) => {
                                return value === 1 ? '系统' : '自定义';
                            }
                        },
                        {
                            title: '操作',
                            dataIndex: '',
                            width: 140,
                            align: 'center',
                            render: (value, record, index) => {
                                let {type, canDel} = record;
                                if (this._isRootPlatform) {
                                    if (!canDel) {
                                        return null;
                                    }
                                } else {
                                    if (type === 1 || !canDel) {
                                        return null;
                                    }
                                }
                                return (
                                    <>
                                        <FunPermission funId="WebPlatformRoleModify">
                                            <Button size="small"
                                                    onClick={this._onEditClick.bind(this, {record, index})}>编辑</Button>
                                        </FunPermission>
                                        <FunPermission funId="WebPlatformRoleDel">
                                            <Button type="danger" size="small"
                                                    style={({marginLeft: 10})}
                                                    onClick={this._onDelClick.bind(this, {
                                                        record,
                                                        index
                                                    })}>删除</Button>
                                        </FunPermission>
                                    </>
                                )
                            }
                        },
                    ]}/>
            </>
        );
    }
}
